//
// standalone fit program for finantial data
// - just reads finantial data
// - no fit implemented yes
// - see Root macros finFit.cc, finFit2.cc for examples
//

// #define _XOPEN_SOURCE // might be needed for strptime

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

extern "C" {
#include <time.h>
}

//
// build a character map where comma is whitespace
//
struct commactype:
  std::ctype<char>
{
  commactype(): std::ctype<char>(get_table()) {}
  static std::ctype_base::mask const* get_table() {
    static std::ctype_base::mask* rc = 0;
    if (rc == 0) {
      rc = new std::ctype_base::mask[std::ctype<char>::table_size];
      std::fill_n(rc, std::ctype<char>::table_size,
		  std::ctype_base::mask());
      rc[',']  = std::ctype_base::space;
      rc['\n'] = std::ctype_base::space;
    }
    return rc;
  }
};

//
// structure for financial quotations
// - fTime is time in seconds since 1970 divided by 3*10^7
// - quote is quotation
//
struct quote_s {
  quote_s(float fTime_i, float quote_i) :
    fTime(fTime_i), quote(quote_i)
  {}
  float fTime;
  float quote;
};
std::vector<quote_s> quotes;

//
// main
//
int main()
{
  std::string line;
  std::string dateStr;
  float iopen, ihigh, ilow, iclose, ivolume, iadjclose;
  float idate;

  std::ifstream input("VFINX.csv");
  if(!input) {
    std::cerr << "Cannot open input\n";
    return EXIT_FAILURE;
  }

  unsigned int lineNum(0);
  bool couldNotConvert(false);
  struct tm unixTime;
  memset(&unixTime, 0, sizeof(unixTime));

  while(std::getline(input, line)) {
    if (couldNotConvert) {
      std::cerr << "Could not convert line " << lineNum << std::endl;
      std::cerr << "-- " << line << " --" << std::endl;
    }
    lineNum++;
    std::istringstream iss(line);
    iss.imbue(std::locale(std::locale(), new commactype));
    if (iss
	>> dateStr 
	>> iopen >> ihigh >> ilow >> iclose >> ivolume >> iadjclose) {
      couldNotConvert = false;

      strptime(dateStr.c_str(), "%d-%b-%y", &unixTime);
      idate = float(mktime(&unixTime));
      idate /= 3e7;
      quotes.push_back(quote_s(idate, iclose));

#if 0
      std::cout
	<< dateStr
	<< " : " << iclose
	<< " - " << idate
	<< " - " << asctime(&unixTime)
	<< std::endl;
#endif      

    } else {
      //--- first line has headers
      if (lineNum>1) {
	couldNotConvert = true;
      }
    }

  }

  //--- loop on quotes
  for(unsigned int i=0; i < quotes.size(); i++) {
#if 0
    std::cout
      << quotes[i].fTime
      << " : " << quotes[i].quote
      << std::endl;
#endif
  }

  std::cout << "Fit noy yet implemented" << std::endl;

#if 0
  std::copy(values.begin(), values.end(),
	    std::ostream_iterator<int>(std::cout, "\n"));
#endif
  
  return 0;
}

